<template>
    <section>
        <div class="wrap lh40 tc mt5 white pl10 pr10 mb10">
            <p class="fs16 bgred" @click.stop="showCart('up')">
                <img class="mr5" :src="imgBuyUp" width="16" height="16" alt>
                买涨
                <span class="fs14 mr30">{{curQuota.askPrice|formatPoint(this.curVariety.marketPoint)}}</span>
            </p>
            <aside class="bgwhite" @click="showFlashCart=!showFlashCart">
                <img :src="flash?imgFlash:imgFlashOff" width="16" height="16" alt>
                <h4 class="lh20" :class="flash?'yellow':'fontc3'">{{flash?'开启':'关闭'}}</h4>
            </aside>
            <p class="fs16 bggreen" @click.stop="showCart('down')">
                <span class="fs14 ml30">{{curQuota.bidPrice|formatPoint(this.curVariety.marketPoint)}}</span>
                买跌
                <img class="ml5" :src="imgBuyDown" width="16" height="16" alt>
            </p>
        </div>
        <div class="toast" v-show="showFlashCart">
            <transition name="slide-fade">
                <div class="flash pb10 bgwhite" v-show="showFlashCart">
                    <h4 class="lh30 fs14 tl ml10 pt10 bold">
                        <span class="fl"></span>
                        闪电下单
                        <i class="iconfont icon-guanbi fr mr15" @click="showFlashCart=!showFlashCart"></i>
                    </h4>
                    <div class="line ml10 mr10 mb10"></div>
                    <ul class="ml10 mr10 pb10">
                        <li class="lh25 clearfix">
                            <strong class="fl">交易手数</strong>
                            <div class="fl">
                                <span
                                    class="fl box mr5"
                                    :class="{active:curHand==hand}"
                                    @click="clickHand(hand)"
                                    :key="idx"
                                    v-for="(hand,idx) in curHandArr"
                                >
                                    {{hand
                                    + '手'}}
                                </span>
                            </div>
                        </li>
                        <li class="lh25 clearfix mt10 flex">
                            <strong class="fl">保证金(￥)</strong>
                            <div class="fl flex1">
                                <span
                                    class="fl box mr5 mb5"
                                    :class="{active:idx==curAssetsIdx}"
                                    v-for="(item,idx) in marginBeat"
                                    @click="changeMarginBeat(idx)"
                                    v-show="idx>2?!foldMarginBeat:true"
                                    :key="idx"
                                >{{item*curHand*getBasePeiZi.ratio|formatMoney()}}</span>
                                <span
                                    class="fl arrow-box iconfont"
                                    :class="foldMarginBeat?'icon-zhankaixia':'icon-shouqishang'"
                                    @click="foldMarginBeat=!foldMarginBeat"
                                ></span>
                            </div>
                        </li>

                        <li class="lh25 mt5 clearfix">
                            <strong class="fl">合计支付</strong>
                            <div class="fl fee">
                                <p class="tl">
                                    ￥{{(marginBeatMoney+fee*curHand)*getBasePeiZi.ratio|formatMoney()}}
                                    <span
                                        class="dbi arrow-box tc ml10 iconfont"
                                        :class="foldText?'icon-zhankaixia':'icon-shouqishang'"
                                        @click="foldText=!foldText"
                                    ></span>
                                </p>
                            </div>
                        </li>
                        <li class="lh25 mt5 clearfix" v-show="!foldText">
                            <strong class="fl">交易综合费</strong>
                            <div class="fl fee">
                                <p class="tl">￥{{fee*curHand*getBasePeiZi.ratio|formatMoney()}}</p>
                            </div>
                        </li>
                    </ul>
                    <div class="flash-btn fs14 ml10 mr10" v-show="!flash">
                        <p
                            class="bgyellow white"
                            @click="() => {
                                flash=true;
                                showFlashCart=false;
                            }"
                        >开启</p>
                    </div>
                    <div class="flash-btn fs14 ml10 mr10 white" v-show="flash">
                        <p class="bgred" @click="()=>{flash=false;showFlashCart=false;}">关闭</p>
                        <p class="bggreen ml10" @click="()=>{flash=true;showFlashCart=false;}">保存</p>
                    </div>
                </div>
            </transition>
        </div>
    </section>
</template>
<script>
import { mapState, mapGetters, mapMutations } from 'vuex'
import { orderNewOrderSubmitNewOrder } from '@api/order.js'
import axios from 'axios'
export default {
	name: 'Buy',
	data() {
		return {
			imgBuyUp: './static/imgs/buyup.svg',
			imgBuyDown: './static/imgs/buydown.svg',
			imgFlash: './static/imgs/flash.svg',
			imgFlashOff: './static/imgs/flashoff.svg',

			// 闪电下单的设置
			showFlashCart: false, // 是否显示下单页面
			flash: false, //闪电下单开关
			curAssetsIdx: 1,
			//是否是角模式
			curHand: 0,
			//能否下单
			orderKey: true,

			// 折叠内容
			foldText: true,
			foldMarginBeat: true
		}
	},
	mounted() {},

	beforeDestroy() {
		//如果购物车显示就隐藏
		if (this.cartShow) {
			this.$store.commit('setCartShow')
		}
	},

	computed: {
		...mapState(['gold', 'curQuota','topupAuth', 'tradeTime', 'userInfo', 'curVariety', 'cartShow']),
		...mapGetters(['getBasePeiZi']),

		curHandArr() {
			if (this.getBasePeiZi && this.getBasePeiZi.assets) {
				return this.getBasePeiZi.assets[this.curAssetsIdx].handsMultiple
			} else {
				return []
			}
		},
		marginBeat() {
			if (this.getBasePeiZi && this.getBasePeiZi.assets) {
				return this.getBasePeiZi.assets.map((value, idx, arr) => {
					return value.marginBeat
				})
			} else {
				return []
			}
		},
		minHand() {
			if (this.getBasePeiZi && this.getBasePeiZi.assets) {
				return this.getBasePeiZi.assets[this.curAssetsIdx].minHands
			} else {
				return 0
			}
		},
		maxHand() {
			if (this.getBasePeiZi && this.getBasePeiZi.assets) {
				return this.getBasePeiZi.assets[this.curAssetsIdx].maxHands
			} else {
				return 0
			}
		},
		fee() {
			if (this.getBasePeiZi) {
				return this.getBasePeiZi.fees
			} else {
				return 0
			}
		},
		marginBeatMoney() {
			if (this.getBasePeiZi && this.getBasePeiZi.assets) {
				return this.getBasePeiZi.assets[this.curAssetsIdx].marginBeat * this.curHand
			} else {
				return 0
			}
		}
	},
	methods: {
		...mapMutations(['setCartShow', 'setToOrder']),
		showCart(pram) {
			//开启了闪电下单
			if (this.flash) {
				this.submitOrder(pram)
				//关闭了闪电下单
			} else {
				if (this.userInfo.userPhone) {
					//如果登录了就可以购买
					this.$store.commit('setCartShow', pram)
				} else {
					this.$router.push({
						path: '/login'
					})
				}
			}
		},

		// 领取金币
		getGold() {
			Indicator.open()
			// /user/shopping/getScore.do
			axios.get('/user/shopping/getScore.do').then(res => {
				Indicator.close()
				res = res.data
				MessageBox('', res.msg)
			})
		},
		// flash
		clickHand(hand) {
			if (hand) {
				this.curHand = hand
			}
		},
		changeMarginBeat(idx) {
			this.curAssetsIdx = idx
		},
		submitOrder(direction) {
			if (!this.orderKey) return
			// Toast('市价模式下单中');

			if (direction == 'up') {
				var direction = 1
				var price = this.curQuota.bidPrice
			} else if (direction == 'down') {
				var direction = 0
				var price = this.curQuota.askPrice
			} else {
				alert('direction 出错')
				return
			}

			const params = {
				handsNum: +this.curHand,
				payType: this.gold ? 0 : 1,
				varietyId: this.curVariety.varietyId,
				orderPrice: price,
				stopWinBeat: this.getBasePeiZi.assets[this.curAssetsIdx].stopWinBeat[1],
				assetsId: this.getBasePeiZi.assets[this.curAssetsIdx].assetsId,
				direction: direction,
				orderMode: 1,
				tradeMode: 0 //0元1角
			}
			this.orderKey = false
			Indicator.open('提交订单中')
			orderNewOrderSubmitNewOrder(params)
				.then(res => {
					Indicator.close()
					if (res.code == 200) {
						if (params.payType === 1) {
							_hmt.push([
								'_trackOrder',
								{
									orderId: new Date().toString(),
									orderTotal: +(this.marginBeatMoney + this.fee * this.curHand) * this.getBasePeiZi.ratio,
									skuId: window.userPhone,
									skuName: '闪电,' + new Date().toString(),
									category: this.curVariety.varietyName,
									Quantity: params.handsNum,
									item: [
										{
											skuId: window.userPhone,
											skuName: '闪电,' + new Date().toString(),
											category: this.curVariety.varietyName,
											Price: (+(this.marginBeatMoney + this.fee * this.curHand) * this.getBasePeiZi.ratio) / params.handsNum,
											Quantity: params.handsNum
										}
									]
								}
							])
						}
                        setTimeout(() => {
                            this.$store.dispatch('getUserInfo')
                        }, 1000);
						MessageBox.confirm('下单成功，是否查看持仓订单?', '闪电下单').then(action => {
							this.$store.commit('setToOrder', true) //chart 会watch 这个值，如果变为true就会跳转
						})
					} else {
                        if (res.msg === '下单失败,失败原因:余额不足' && params.payType === 1) {
                            MessageBox.confirm(' ', {
                                title: '闪电下单',
                                message: '实盘账户余额不足，请立即充值',
                                confirmButtonText: '去充值',
                                confirmButtonClass: 'red'
                            }).then(action => {
                                if (action === 'confirm') {
                                    this.getTopupAuth()
                                }
                            })
                        } else {
						    MessageBox('挂单模式', res.msg)
                        }
                    }
                    Indicator.close()
                    this.orderKey = true
				})
				.catch((err) => {
                    console.log('err-->' ,err)
                    Indicator.close()
                    this.orderKey = true
					MessageBox('闪电下单', err.msg)
				})
		},
		initBaseCart() {
			;(this.showFlashCart = false), // 是否显示下单页面
				(this.flash = false), //闪电下单开关
				(this.curAssetsIdx = 1)
			this.curHand = 0
			this.orderKey = true
        },
        getTopupAuth() {
            if (Object.keys(this.topupAuth).length === 0) {
                this.$router.push({
                    path: "/login",
                });
            } else if (this.topupAuth.identify === 1 && !this.topupAuth.cardState) {
                MessageBox.confirm("", {
                    title: "充值",
                    message: "为了您的资金安全，请前去绑卡",
                    confirmButtonText: "去绑定",
                    confirmButtonClass: "red"
                }).then(() => {
                    this.$router.push({
                        path: "/account/bindbank",
                    });
                });
            } else {
                window.location.href = "./account/paySelect.html";
            }
        }
	},
	watch: {
		getBasePeiZi(newer, old) {
			//初始化
			this.initBaseCart()

			this.curAssetsIdx = 1

			//初始化手数为最小手数
			this.curHand = +newer.assets[this.curAssetsIdx].handsMultiple[0]
		}
	}
}
</script>
<style scoped lang='scss'>
.wrap {
	display: flex;
	justify-content: space-between;
	height: rem(40px);
}

.wrap p {
	width: 50%;
	height: rem(40px);
}

.wrap p:first-child {
	border-top-left-radius: rem(5px);
	border-bottom-left-radius: rem(5px);
}

.wrap p:last-child {
	border-top-right-radius: rem(5px);
	border-bottom-right-radius: rem(5px);
}

.fee p {
	width: auto;
}

.wrap p img {
	vertical-align: rem(-3px);
}

.blue {
	background-color: #3377ff;
}

main * {
	touch-action: manipulation !important;
}

aside {
	border-radius: rem(20px);
	position: absolute;
	width: rem(60px);
	height: rem(40px);
	left: 50%;
	transform: translateX(-50%);
	text-align: center;
}

aside img {
	display: block;
    margin: 0 auto;
    height: rem(16px);
    height: rem(16px);
	margin-top: rem(5px);
}

aside h4 {
	width: rem(60px);
	line-height: rem(20px);
	height: rem(20px);
}

.toast {
	position: fixed;
	width: 100%;
	height: 100%;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.3);
}

svg {
	width: ren(20px);
	height: rem(20px);
	color: #707284;
}

/* flash */
.flash {
	position: absolute;
	left: 0;
	bottom: 0;
	width: 100%;
	height: rem(230px);
	overflow-y: scroll;
}

strong {
	width: rem(80px);
	text-align: left;
}

.box {
	min-width: rem(63px);
	width: auto;
	box-sizing: border-box;
	border-radius: rem(2px);
	border: 1px solid #aaaaaa;
}

.arrow-box {
	border: 1px solid #aaaaaa;
	border-radius: rem(2px);
	width: rem(25px);
	line-height: rem(23px);
	height: rem(23px);
	color: #707284;
}

.line {
	border-bottom: 1px solid #c8c8c8;
}

.cube {
	width: rem(30px);
	background-color: #474958;
	box-sizing: border-box;
	border-radius: 2px;
}

input {
	width: rem(80px);
	border: 0 none;
	outline: 0 none;
	text-align: center;
	background-color: transparent;
	color: #fff;
}

.buy-button {
	display: flex;
	justify-content: space-between;
	position: fixed;
	width: 100%;
	padding-left: rem(20px);
	padding-right: rem(20px);
	bottom: rem(10px);
}

.buy-button p {
	width: 50%;
	color: #fff;
	border-radius: rem(20px);
}

.active {
	color: #fff;
	background-color: #ef9d2e;
	border-color: #ef9d2e;
}

.flash-btn {
	display: flex;
	justify-content: space-around;
}

.flash-btn p {
	flex: 1;
	border-radius: rem(4px);
	line-height: rem(36px);
}

.flex {
	display: flex;
}

.flex1 {
	flex: 1;
}

ul li svg {
	vertical-align: rem(-2px);
}

.slide-fade-enter-active {
	transition: all 0.3s ease;
}

.slide-fade-leave-active {
	transition: all 0.3s ease;
}

.slide-fade-enter,
	.slide-fade-leave-to

	/* .slide-fade-leave-active for below version 2.1.8 */
		 {
	transform: translateY(rem(300px));
}
</style>